package com.bkitclub.mobiledevcamp.horseword.model;

import com.bkitclub.mobiledevcamp.horseword.model.data.DataSource;

public class DatabaseController {
	private final long[] dict;
	private final int dictLeng;
	public static final long power27[] = { 1, 27, 729, 19683, 531441, 14348907,
			387420489, 10460353203L };

	public DatabaseController() {
		dict = DataSource.getData();
		dictLeng = dict.length - 1;
	}
	
	public boolean search(String str) {
		str = standarStr(str);
		long number = calNumber(str);
		
		int min = 0;
		int max = dictLeng;
		int mid;
		while(min < max) {
			mid = (min + max) >> 1;
			if(dict[mid] == number)
				return true;
			else if(dict[mid] > number)
				min = mid + 1;
			else
				max = mid - 1;
			
		}
		return false;
	}
	
	

	private static int findE(char c) {
		if (c == ' ') {
			return 0;
		} else {
			return c - 64;
		}
	}

	private static long calNumber(String str) {
		char[] arr = str.toCharArray();
		long result = 0;
		if (arr.length != 8) {
			System.out.println(str);
		}
		for (int i = 0; i < 8; i++) {
			result += findE(arr[i]) * power27[7 - i];
		}
		return result;
	}

	private String standarStr(String str) {
		int len = 8 - str.length();

		switch (len) {
		case 1:
			return str + " ";
		case 2:
			return str + "  ";
		case 3:
			return str + "   ";
		case 4:
			return str + "    ";
		case 5:
			return str + "     ";
		}
		return str;
	}

}
